package com.eascs.web.o2o.report.task;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.app.runtime.RuntimeSetting;
import com.eascs.common.util.StopWatch;
import com.eascs.common.util.StringUtil;
import com.eascs.notify.constant.ModelResult;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailNotifyResponse;
import com.eascs.notify.mail.MailSendType;
import com.eascs.web.o2o.report.constants.FefundConstants;
import com.eascs.web.o2o.report.constants.SendType;
import com.eascs.web.o2o.report.dto.FtpConfig;
import com.eascs.web.o2o.report.dto.MessageDTO;
import com.eascs.web.o2o.report.dto.MessageReceiver;
import com.eascs.web.o2o.report.entity.WfEmail;
import com.eascs.web.o2o.report.entity.WfMessage;
import com.eascs.web.o2o.report.service.EmailService;
import com.eascs.web.o2o.report.service.MessageService;
import com.eascs.web.o2o.report.service.MsgService;
import com.eascs.web.o2o.report.util.FtpUtil;
import com.eascs.web.o2o.report.util.MailUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.*;

@Component("messageTask")
public class MessageTask {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${msg.email.host}")
	private String host;	//smtp
	
	@Value("${msg.email.title}")
	private String title;	//邮件标题
	
	@Value("${msg.email.sender}")
	private String sender;	//发送者邮件
	
	@Value("${msg.email.sender.password}")
	private String password;	//发送者邮件密码
	@Value("${ftp.path}")
	private String	path;		// 路径
	
	@Value("${msg.message.sendername}")
	private String sendername;	//短信发送者
	@Inject
	MessageService messageService;
	@Inject
	MsgService msgService;
	@Inject
    EmailService emailService;
	
	@Inject
	MailUtil mailUtil;
	

	@Scheduled(cron = "0 */5 * * * ?")
	public void msgSend() {
		logger.info("短信定时任务开始......");
		StopWatch stopWatch = new StopWatch();
		//从DB读取未发的信息
		List<WfMessage> messageList=msgService.findWfMessage(0);
		SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
		if(!CollectionUtils.isEmpty(messageList)){
			for (WfMessage wfMessage : messageList) {
				MessageDTO	dto=new MessageDTO();
				if(wfMessage.getSendType().equals("SCHEDULE")){//定时发送
					dto.setSendType(SendType.ONTIME);//定时
					if(wfMessage.getScheduleSendDateTime()==null||!send(wfMessage.getScheduleSendDateTime())||!("群发短信").equals(wfMessage.getSystemCode())){
						break;
					}
				} else{
					dto.setSendType(SendType.NOW);//立即
				}
				List<MessageReceiver> receivers=new ArrayList<>();
				MessageReceiver receiver=new MessageReceiver();
				receiver.setName(wfMessage.getReceiveName());
				receiver.setPhone(wfMessage.getReceiveTelphone());
				receivers.add(receiver);
				dto.setReceivers(receivers);
				dto.setMsgContent(wfMessage.getContent());
				dto.setSenderName(sendername);
				dto.setSendTime(s.format(new Date()));
				dto.setId(wfMessage.getMessageId());
				
				RuntimeSetting runtimeSetting = RuntimeSetting.get();
				boolean flag = false;
				if (runtimeSetting.getEnv().equals(FefundConstants.ENV_PROD)) {
					flag = messageService.sendMsg(dto);

					if (flag) {
						msgService.updateState(wfMessage.getMessageId());//成功之后修改短信状态
					} else {
						msgService.updateCounts(wfMessage.getMessageId());
						logger.info("发送短信失败：接收人[{}],接收人手机[{}],创建人[{}]", wfMessage.getReceiveName(), wfMessage.getReceiveTelphone(), sendername);
					}
				} else {
					logger.info("非正式环境不发送短信：接收人[{}],接收人手机[{}],创建人[{}]", wfMessage.getReceiveName(), wfMessage.getReceiveTelphone(), sendername);
				}

				
			}
			
		} else{
			logger.info("没有短信需要发送");
		}
		
		logger.info("短信定时任务结束，共耗时：[{}]秒", stopWatch.elapsedTime()/1000);
	}
	
	
	public boolean send(Date date){
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	     Calendar afterTime = Calendar.getInstance();
	     afterTime.add(Calendar.MINUTE, 10);// 10分钟之前的时间
	     Long afterD =afterTime.getTime().getTime();
	     Calendar now = Calendar.getInstance();
	     now.add(Calendar.MINUTE, -5);// -5分钟之前的时间
	     Long nowD = now.getTime().getTime();
	     Long dateD = date.getTime();
	     if(dateD>nowD&&nowD<afterD){
	    	 return true;
	     }else{
	    	 return false;
	     }
	}
	
	
	
	

	@Scheduled(cron = "0 */5 * * * ?")
	public void mailGenerSend() {
	logger.info("邮件定时任务开始......");
		StopWatch stopWatch = new StopWatch();
		//从DB中读取所以未发送且发送次数小于三次的数据，发送完成后更新掉状态和发送时间
		List<WfEmail> emailList=emailService.findWfEmail(0);
		if(!CollectionUtils.isEmpty(emailList)){
			for (WfEmail wfEmail : emailList) {
				MailNotifyRequest mailNotifyRequest=new MailNotifyRequest();
				setParam(wfEmail, mailNotifyRequest);
				ModelResult<MailNotifyResponse> model=null;
				RuntimeSetting runtimeSetting = RuntimeSetting.get();
				if(runtimeSetting.getEnv().equals(FefundConstants.ENV_PROD)&&!(MailSendType.SCHEDULE).equals(wfEmail.getMailSendType())){
					try {
						 model=mailUtil.sendMail(mailNotifyRequest);
						 if(model.isSuccess()){
							 logger.info("邮件发送完成，插库信息为：[{}]", model.getModel().getResponseId());
							 emailService.updateState(wfEmail.getEmailId());
						 }else{
							 logger.error("邮件发送异常，异常code为：[{}],异常内容为：[{}]", model.getErrCode(),model.getErrMsg());
						 emailService.updateCounts(wfEmail.getEmailId());
						 }
					} catch (Exception e) {
					logger.error("邮件发送接口调用异常",e.getMessage());
					}
				}
			}
		} else{
		logger.info("没有邮件需要发送");
		}
	
		logger.info("邮件定时任务结束，共耗时：[{}]秒", stopWatch.elapsedTime()/1000);
	}

	private void setParam(WfEmail wfEmail, MailNotifyRequest mailNotifyRequest) {
		mailNotifyRequest.setTitle(wfEmail.getTitle());
		mailNotifyRequest.setContent(wfEmail.getContent());
		mailNotifyRequest.setSystemCode(wfEmail.getSystemCode());
		mailNotifyRequest.setMailSendType(MailSendType.SCHEDULE);
		mailNotifyRequest.setRecipientTo(wfEmail.getRecipients());
		mailNotifyRequest.setRequestId(wfEmail.getRequestId());
		mailNotifyRequest.setRequestDateTime(wfEmail.getRequestDateTime());
		mailNotifyRequest.setRecipientCc(wfEmail.getCc());
		mailNotifyRequest.setRecipientBcc(wfEmail.getRecipientBcc());
		mailNotifyRequest.setFrom(wfEmail.getSender());
		
		Set<String> fileSet=new HashSet<>();
		if(StringUtil.isNotBlank(wfEmail.getAppendix())){
			try {
				fileSet=FtpUtil.startDownload(FtpConfig.getInstance(), path, wfEmail.getAppendix());
			} catch (Exception e) {
				logger.info("发送邮件拉取FTP文件异常：[{}]", e.getMessage());
			}
		}
		if(!CollectionUtils.isEmpty(fileSet)){
			
			List<String> attach = new ArrayList<>();
			attach.add(path);
			mailNotifyRequest.setAttachmentPath(attach.toString().substring(1, attach.toString().length()-1));
		}
	}
	
	
	
	
}
